<?php

namespace Home\Service;

use Home\Common\FIdConst;

/**
 * 货权转移Service
 *
 * @author 李静波
 */
class GOBillService extends PSIBaseService {
	private $LOG_CATEGORY = "货权转移";

	/**
	 * 新建或编辑的时候，获得货权转移单的详情
	 */
	public function goBillInfo($params) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$id = $params["id"];
		
		$us = new UserService();
		$result = array();
		$result["canEditGoodsPrice"] = $this->canEditGoodsPrice();
		$result["showAddCustomerButton"] = $us->hasPermission(FIdConst::CUSTOMER);
		
		// 新建货权转移单
		$result["bizUserId"] = $us->getLoginUserId();
		$result["bizUserName"] = $us->getLoginUserName();
		
		$ts = new BizConfigService();
		$db = M();
		$sql = "select value from t_config where id = '2002-02' ";
		$data = $db->query($sql);
		if ($data) {
			$warehouseId = $data[0]["value"];
			$sql = "select id, name from t_warehouse where id = '%s' ";
			$data = $db->query($sql, $warehouseId);
			if ($data) {
				$result["warehouseId"] = $data[0]["id"];
				$result["warehouseName"] = $data[0]["name"];
			}
		}
			
		if ($id) {
			// 编辑
			$db = M();
			$sql = "select 
						w.warehouse_id,
						w.goods_id,
						w.sn_note,
						w.memo,
						w.biz_user_id,
						w.ref, 
						w.id, 
						w.bizdt, 
						c1.name as fromgoodsownername,
						c2.name as togoodsownername,
						w.from_goodsowner_id,
						w.to_goodsowner_id,
						u.name as biz_user_name,
						w.goods_count,
						goods.name as goods_name,
						goods.code as goods_code,
						goods.spec as goods_spec,
						goods_unit.name as unit_name,
						user.name as input_user_name, 
						h.name as warehouse_name, 
						w.bill_status, 
						w.date_created, 
						w.receiving_type, 
						w.memo,
						w.bill_memo,
						w.sn_note
					from 
					t_goodsowner_bills w
						left join t_goodsowner c1 on w.from_goodsowner_id = c1.id
						left join t_goodsowner c2 on w.to_goodsowner_id = c2.id	
					, t_user u, t_user user, t_warehouse h ,
					 t_goods goods,
					 t_goods_unit goods_unit
					where  (w.biz_user_id = u.id) 
					  and (w.input_user_id = user.id) and (w.warehouse_id = h.id)
					  and (goods.id = w.goods_id) and (goods_unit.id = goods.unit_id)
					  and w.id = '%s'";
			$data = $db->query($sql, $id);
			if ($data) {
				$result["ref"] = $data[0]["ref"];
				$result["fromGoodsOwnerName"] = $data[0]["fromgoodsownername"];
				$result["toGoodsOwnerName"] = $data[0]["togoodsownername"];
				$result["fromGoodsOwnerId"] = $data[0]["from_goodsowner_id"];
				$result["toGoodsOwnerId"] = $data[0]["to_goodsowner_id"];
				$result["billStatus"] = $data[0]["bill_status"];
				$result["bizDT"] = date("Y-m-d", strtotime($data[0]["bizdt"]));
				$result["customerId"] = $data[0]["customer_id"];
				$result["customerName"] = $data[0]["customer_name"];
				$result["warehouseId"] = $data[0]["warehouse_id"];
				$result["warehouseName"] = $data[0]["warehouse_name"];
				$result["bizUserId"] = $data[0]["biz_user_id"];
				$result["bizUserName"] = $data[0]["biz_user_name"];
				$result["receivingType"] = $data[0]["receiving_type"];
				$result["billMemo"] = $data[0]["bill_memo"];
				
				$items[0]["goodsId"] = $data[0]["goods_id"];
				$items[0]["goodsCode"] = $data[0]["goods_code"];
				$items[0]["goodsSpec"] = $data[0]["goods_spec"];
				$items[0]["goodsCount"] = $data[0]["goods_count"];
				$items[0]["goodsName"] = $data[0]["goods_name"];
				$items[0]["unitName"] = $data[0]["unit_name"];
				$items[0]["memo"] = $data[0]["memo"];
				$items[0]["sn"] = $data[0]["sn_note"];
			} 
				
			$result["items"] = $items;
				
		}
		
		return $result;
	}

	/**
	 * 判断是否可以编辑商品货权转移单价
	 *
	 * @return boolean true:可以编辑货权转移单价
	 */
	private function canEditGoodsPrice() {
		// 首先判断业务设置中是否允许货权转移编辑货权转移单价（全局控制）
		$db = M();
		$sql = "select value from t_config where id = '2002-01' ";
		$data = $db->query($sql);
		if (! $data) {
			return false;
		}
		
		$v = intval($data[0]["value"]);
		if ($v == 0) {
			return false;
		}
		
		$us = new UserService();
		// 在业务设置中启用编辑的前提下，还需要判断对应的权限（具体的用户）
		return $us->hasPermission("2002-01");
	}

	/**
	 * 新增或编辑货权转移单
	 */
	public function editGOBill($params) {
		if ($this->isNotOnline()) {
			return $this->notOnlineError();
		}
		
		$json = $params["jsonStr"];
		$bill = json_decode(html_entity_decode($json), true);
		if ($bill == null) {
			return $this->bad("传入的参数错误，不是正确的JSON格式");
		}
		
		$id = $bill["id"];
		$bizDT = $bill["bizDT"];
		$warehouseId = $bill["warehouseId"];
		$fromGoodsownerId = $bill["fromGoodsownerId"];
		$toGoodsownerId = $bill["toGoodsownerId"];
		$bizUserId = $bill["bizUserId"];
		$receivingType = $bill["receivingType"];
		$billMemo = $bill["billMemo"];
		$items = $bill["items"];
		
		
		$db = M();
		$db->startTrans();
		
		// 检查货主
		$sql = "select count(*) as cnt from t_goodsowner where id = '%s' ";
		$data = $db->query($sql, $fromGoodsownerId);
		$cnt = $data[0]["cnt"];
		if ($cnt != 1) {
			$db->rollback();
			return $this->bad("选择的“从货主”不存在，无法保存数据");
		}
		
		$sql = "select count(*) as cnt from t_goodsowner where id = '%s' ";
		$data = $db->query($sql, $toGoodsownerId);
		$cnt = $data[0]["cnt"];
		if ($cnt != 1) {
			$db->rollback();
			return $this->bad("选择的“到货主”不存在，无法保存数据");
		}
		
		// 检查仓库
		$sql = "select count(*) as cnt from t_warehouse where id = '%s' ";
		$data = $db->query($sql, $warehouseId);
		$cnt = $data[0]["cnt"];
		if ($cnt != 1) {
			$db->rollback();
			return $this->bad("选择的仓库不存在，无法保存数据");
		}
		
		// 检查业务员
		$sql = "select count(*) as cnt from t_user where id = '%s' ";
		$data = $db->query($sql, $bizUserId);
		$cnt = $data[0]["cnt"];
		if ($cnt != 1) {
			$db->rollback();
			return $this->bad("选择的业务员不存在，无法保存数据");
		}
		
		// 检查业务日期
		if (! $this->dateIsValid($bizDT)) {
			$db->rollback();
			return $this->bad("业务日期不正确");
		}
		
		$idGen = new IdGenService();
		
		$log = null;
		
		if ($id) {
			
			$us = new UserService();
			$dataOrg = $us->getLoginUserDataOrg();
			$companyId = $us->getCompanyId();
				
			$goodsId = $items[0]["goodsId"];
			$goodsCount = floatval($items[0]["goodsCount"]);
			$sn = $items[0]["sn"];
			$memo = $items[0]["memo"];
			
			// 编辑
			$sql = "select ref, bill_status, data_org, company_id from t_goodsowner_bills where id = '%s' ";
			$data = $db->query($sql, $id);
			if (! $data) {
				$db->rollback();
				return $this->bad("要编辑的货权转移单不存在");
			}
			$ref = $data[0]["ref"];
			$billStatus = $data[0]["bill_status"];
			if ($billStatus != 0) {
				$db->rollback();
				return $this->bad("货权转移单[单号：{$ref}]已经提交出库了，不能再编辑");
			}
			$dataOrg = $data[0]["data_org"];
			$companyId = $data[0]["company_id"];
			
			$sql = "delete from t_goodsowner_bills where id = '%s' ";
			$rc = $db->execute($sql, $id);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$sql =	"INSERT INTO t_goodsowner_bills(ref,id, bill_status, bizdt, biz_user_id, from_goodsowner_id,
							to_goodsowner_id, date_created, input_user_id, goods_id, goods_count, 
							warehouse_id, receiving_type, sn_note, data_org, memo, bill_memo, company_id)
						VALUES(
								'%s',
								'%s',
								0,
								'%s',
								'%s',
								'%s',
								'%s',
								now(),
								'%s',
								'%s',
								'%f',
								'%s',
								'%s',
								'%s',
								'%s',
								'%s',
								'%s',
								'%s')";
			
			$rc = $db->execute($sql, 
					$ref,
					$id,
					$bizDT,
					$bizUserId,
					$fromGoodsownerId,
					$toGoodsownerId,
					$us->getLoginUserId(),
					$goodsId,
					$goodsCount,
					$warehouseId,
					$receivingType,
					$sn,
					$dataOrg,
					$memo,
					$billMemo,
					$companyId);
			
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$log = "编辑货权转移单，单号 = {$ref}";
		} else {
			$us = new UserService();
			$dataOrg = $us->getLoginUserDataOrg();
			$companyId = $us->getCompanyId();
			
			$goodsId = $items[0]["goodsId"];
			$goodsCount = floatval($items[0]["goodsCount"]);
			$sn = $items[0]["sn"];
			$memo = $items[0]["memo"];
				
			// 新增
			$id = $idGen->newId();
			$ref = $this->genNewBillRef();
			$sql =	"INSERT INTO t_goodsowner_bills(ref,id, bill_status, bizdt, biz_user_id, from_goodsowner_id,
							to_goodsowner_id, date_created, input_user_id, goods_id, goods_count, 
							warehouse_id, receiving_type, sn_note, data_org, memo, bill_memo, company_id)
						VALUES(
								'%s',
								'%s',
								0,
								'%s',
								'%s',
								'%s',
								'%s',
								now(),
								'%s',
								'%s',
								'%f',
								'%s',
								'%s',
								'%s',
								'%s',
								'%s',
								'%s',
								'%s')";
			
			$rc = $db->execute($sql, 
					$ref,
					$id,
					$bizDT,
					$bizUserId,
					$fromGoodsownerId,
					$toGoodsownerId,
					$us->getLoginUserId(),
					$goodsId,
					$goodsCount,
					$warehouseId,
					$receivingType,
					$sn,
					$dataOrg,
					$memo,
					$billMemo,
					$companyId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
	
			// 手工新建货权转移单
			$log = "新增货权转移单，单号 = {$ref}";
		}
		
		// 记录业务日志
		if ($log) {
			$bs = new BizlogService();
			$bs->insertBizlog($log, $this->LOG_CATEGORY);
		}
		
		$db->commit();
		
		return $this->ok($id);
	}

	/**
	 * 生成新的货权转移单单号
	 *
	 * @return string
	 */
	private function genNewBillRef() {
		$bs = new BizConfigService();
		$pre = $bs->getGOBillRefPre();
		
		$mid = date("Ymd");
		
		$sql = "select ref from t_ws_bill where ref like '%s' order by ref desc limit 1";
		$data = M()->query($sql, $pre . $mid . "%");
		$sufLength = 3;
		$suf = str_pad("1", $sufLength, "0", STR_PAD_LEFT);
		if ($data) {
			$ref = $data[0]["ref"];
			$nextNumber = intval(substr($ref, strlen($pre . $mid))) + 1;
			$suf = str_pad($nextNumber, $sufLength, "0", STR_PAD_LEFT);
		}
		
		return $pre . $mid . $suf;
	}

	/**
	 * 获得货权转移单主表列表
	 */
	public function getGobillList($params) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$page = $params["page"];
		$start = $params["start"];
		$limit = $params["limit"];
		
		$billStatus = $params["billStatus"];
		$ref = $params["ref"];
		$fromDT = $params["fromDT"];
		$toDT = $params["toDT"];
		$warehouseId = $params["warehouseId"];
		$fromGoodsownerId = $params["fromGoodsownerId"];
		$toGoodsownerId = $params["toGoodsownerId"];
		$sn = $params["sn"];
		$receivingType = $params["receivingType"];
		
		$db = M();
		$sql = "select w.ref, w.id, w.bizdt, c1.name as fromgoodsownername,
					c2.name as togoodsownername,
					u.name as biz_user_name,
					w.goods_count,
					goods.name as goods_name,
					goods_unit.name as unit_name,
					user.name as input_user_name, h.name as warehouse_name, 
					w.bill_status, w.date_created, w.receiving_type, w.memo 
				from 
				t_goodsowner_bills w
					left join t_goodsowner c1 on w.from_goodsowner_id = c1.id
					left join t_goodsowner c2 on w.to_goodsowner_id = c2.id	
				, t_user u, t_user user, t_warehouse h ,
				 t_goods goods,
				 t_goods_unit goods_unit
				where  (w.biz_user_id = u.id) 
				  and (w.input_user_id = user.id) and (w.warehouse_id = h.id)
				  and (goods.id = w.goods_id) and (goods_unit.id = goods.unit_id)";
		$queryParams = array();
		
		$ds = new DataOrgService();
		$rs = $ds->buildSQL(FIdConst::WAREHOUSING_SALE, "w");
		if ($rs) {
			$sql .= " and " . $rs[0];
			$queryParams = $rs[1];
		}
		
		if ($billStatus) {
			$sql .= " and (w.bill_status = %d) ";
			$queryParams[] = $billStatus;
		}
		if ($fromDT) {
			$sql .= " and (w.bizdt >= '%s') ";
			$queryParams[] = $fromDT;
		}
		if ($toDT) {
			$sql .= " and (w.bizdt <= '%s') ";
			$queryParams[] = $toDT;
		}
		if ($fromGoodsownerId) {
			$sql .= " and (w.from_goodsowner_id = '%s') ";
			$queryParams[] = $fromGoodsownerId;
		}
		if ($warehouseId) {
			$sql .= " and (w.warehouse_id = '%s') ";
			$queryParams[] = $warehouseId;
		}
	
		$sql .= " order by w.bizdt desc,w.date_created desc limit %d, %d";
		$queryParams[] = $start;
		$queryParams[] = $limit;
		$data = $db->query($sql, $queryParams);
		$result = array();
		
		foreach ( $data as $i => $v ) {
			$result[$i]["id"] = $v["id"];
			$result[$i]["ref"] = $v["ref"];
			$result[$i]["bizDate"] = date("Y-m-d", strtotime($v["bizdt"]));
			$result[$i]["customerName"] = $v["customer_name"];
			$result[$i]["warehouseName"] = $v["warehouse_name"];
			$result[$i]["inputUserName"] = $v["input_user_name"];
			$result[$i]["bizUserName"] = $v["biz_user_name"];
			$result[$i]["billStatus"] = $v["bill_status"] == 0 ? "待转权" : "已转权";
			$result[$i]["dateCreated"] = $v["date_created"];
			$result[$i]["receivingType"] = $v["receiving_type"];
			$result[$i]["memo"] = $v["memo"];
			$result[$i]["fromGoodsownerName"] = $v["fromgoodsownername"];
			$result[$i]["toGoodsownerName"] = $v["togoodsownername"];
			$result[$i]["goodsCount"] = $v["goods_count"];
			$result[$i]["unitName"] = $v["unit_name"];
			$result[$i]["goodsName"] = $v["goods_name"];
			
		}
		
		$sql = "select count(*) as cnt 
				from t_goodsowner_bills w, t_goodsowner c, t_user u, t_user user, t_warehouse h 
				where (w.from_goodsowner_id = c.id) and (w.biz_user_id = u.id) 
				  and (w.input_user_id = user.id) and (w.warehouse_id = h.id) ";
		$queryParams = array();
		
		$ds = new DataOrgService();
		$rs = $ds->buildSQL(FIdConst::WAREHOUSING_SALE, "w");
		if ($rs) {
			$sql .= " and " . $rs[0];
			$queryParams = $rs[1];
		}
		
		if ($billStatus != - 1) {
			$sql .= " and (w.bill_status = %d) ";
			$queryParams[] = $billStatus;
		}
		if ($ref) {
			$sql .= " and (w.ref like '%s') ";
			$queryParams[] = "%{$ref}%";
		}
		if ($fromDT) {
			$sql .= " and (w.bizdt >= '%s') ";
			$queryParams[] = $fromDT;
		}
		if ($toDT) {
			$sql .= " and (w.bizdt <= '%s') ";
			$queryParams[] = $toDT;
		}
		if ($fromGoodsownerId) {
			$sql .= " and (w.from_goodsowner_id = '%s') ";
			$queryParams[] = $fromGoodsownerId;
		}
		if ($warehouseId) {
			$sql .= " and (w.warehouse_id = '%s') ";
			$queryParams[] = $warehouseId;
		}
		
		if ($receivingType != - 1) {
			$sql .= " and (w.receiving_type = %d) ";
			$queryParams[] = $receivingType;
		}
		
		$data = $db->query($sql, $queryParams);
		$cnt = $data[0]["cnt"];
		
		return array(
				"dataList" => $result,
				"totalCount" => $cnt
		);
	}

	/**
	 * 获得某个货权转移单的明细记录列表
	 */
	public function goBillDetailList($params) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$billId = $params["billId"];
		$sql = "select d.id, g.code, g.name, g.spec, u.name as unit_name, d.goods_count, 
				d.goods_price, d.goods_money, d.sn_note, d.memo ,d.outWHCarNo,d.needer,d.upPrice,d.upPersonPrice
				from t_ws_bill_detail d, t_goods g, t_goods_unit u 
				where d.wsbill_id = '%s' and d.goods_id = g.id and g.unit_id = u.id 
				order by d.show_order";
		$data = M()->query($sql, $billId);
		$result = array();
		
		foreach ( $data as $i => $v ) {
			$result[$i]["id"] = $v["id"];
			$result[$i]["goodsCode"] = $v["code"];
			$result[$i]["goodsName"] = $v["name"];
			$result[$i]["goodsSpec"] = $v["spec"];
			$result[$i]["unitName"] = $v["unit_name"];
			$result[$i]["goodsCount"] = $v["goods_count"];
			$result[$i]["goodsPrice"] = $v["goods_price"];
			$result[$i]["goodsMoney"] = $v["goods_money"];
			
			$result[$i]["outWHCarNo"] = $v["outwhcarno"];
			$result[$i]["needer"] = $v["needer"];
			$result[$i]["upPrice"] = $v["upprice"];
			$result[$i]["upPersonPrice"] = $v["uppersonprice"];
			
			$result[$i]["sn"] = $v["sn_note"];
			$result[$i]["memo"] = $v["memo"];
		}
		
		return $result;
	}
	
	/**
	 * 获得所有货权转移单的明细记录列表
	 */
	public function wsAllBillDetailList($params) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$page = $params["page"];
		$start = $params["start"];
		$limit = $params["limit"];
		
		$ref = $params["ref"];
		$customerId = $params["customerId"];
		$warehouseId = $params["warehouseId"];
		$goodsId = $params["goodsId"];
		$fromDT = $params["fromDT"];
		$toDT = $params["toDT"];
		$sn = $params["sn"];
		
		$queryParams = array();
		
		$sql = "select 
					bill.bill_status,
					bill.ref,
					bill.bizdt,
					d.id, 
					warehouse.name as warehouse_name,
					customer.name as customer_name,
					g.code, g.name, g.spec, u.name as unit_name, d.goods_count,
				d.goods_price, d.goods_money, d.sn_note, d.memo ,d.outWHCarNo,d.needer,d.upPrice,d.upPersonPrice
				from t_ws_bill_detail d
					left join t_ws_bill bill on d.wsbill_id = bill.id
					left join t_warehouse warehouse on warehouse.id = bill.warehouse_id
					left join t_customer customer on customer.id = bill.customer_id
					, t_goods g
					, t_goods_unit u
				where d.goods_id = g.id and g.unit_id = u.id
				";
		if ($ref) {
			$sql .= " and (bill.ref = '%s') ";
			$queryParams[] = $ref;
		}
		if ($customerId) {
			$sql .= " and (bill.customer_id = '%s') ";
			$queryParams[] = $customerId;
		}
		if ($warehouseId) {
			$sql .= " and (bill.warehouse_id = '%s') ";
			$queryParams[] = $warehouseId;
		}
		
		if ($goodsId) {
			$sql .= " and (d.goods_id = '%s') ";
			$queryParams[] = $goodsId;
		}
		if ($fromDT) {
			$sql .= " and (bill.bizdt >= '%s') ";
			$queryParams[] = $fromDT;
		}
		if ($toDT) {
			$sql .= " and (bill.bizdt <= '%s') ";
			$queryParams[] = $toDT;
		}
		if ($sn) {
			$sql .= " and (d.sn_note like '%s')";
			$queryParams[] = "%$sn%";
		}
		
		$sql .= " order by bill.bizdt desc, bill.ref desc
				limit %d, %d";
		$queryParams[] = $start;
		$queryParams[] = $limit;
		
		$data = M()->query($sql,$queryParams);
		$result = array();
	
		foreach ( $data as $i => $v ) {
			
			
			$result[$i]["billStatus"] = $v["bill_status"] == 0 ? "待出库" : "已出库";
			
			$result[$i]["id"] = $v["id"];
				
			$result[$i]["ref"] = $v["ref"];
			$result[$i]["bizDate"] = date("Y-m-d",strtotime($v["bizdt"]));
			$result[$i]["warehouseName"] = $v["warehouse_name"];
			$result[$i]["customerName"] = $v["customer_name"];
			
			$result[$i]["goodsCode"] = $v["code"];
			$result[$i]["goodsName"] = $v["name"];
			$result[$i]["goodsSpec"] = $v["spec"];
			$result[$i]["unitName"] = $v["unit_name"];
			$result[$i]["goodsCount"] = $v["goods_count"];
			$result[$i]["goodsPrice"] = $v["goods_price"];
			$result[$i]["goodsMoney"] = $v["goods_money"];
				
			$result[$i]["outWHCarNo"] = $v["outwhcarno"];
			$result[$i]["needer"] = $v["needer"];
			$result[$i]["upPrice"] = $v["upprice"];
			$result[$i]["upPersonPrice"] = $v["uppersonprice"];
				
			$result[$i]["sn"] = $v["sn_note"];
			$result[$i]["memo"] = $v["memo"];
		}
	
		return $result;
	}

	/**
	 * 删除货权转移单
	 */
	public function deleteGOBill($params) {
		if ($this->isNotOnline()) {
			return $this->notOnlineError();
		}
		
		$id = $params["id"];
		$db = M();
		$db->startTrans();
		
		$sql = "select ref, bill_status from t_goodsowner_bills where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			$db->rollback();
			return $this->bad("要删除的货权转移单不存在");
		}
		$ref = $data[0]["ref"];
		$billStatus = $data[0]["bill_status"];
		if ($billStatus != 0) {
			$db->rollback();
			return $this->bad("货权转移单已经提交出库，不能删除");
		}
		
		$sql = "delete from t_goodsowner_bills where id = '%s' ";
		$rc = $db->execute($sql, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		
		$log = "删除货权转移单，单号: {$ref}";
		$bs = new BizlogService();
		$bs->insertBizlog($log, $this->LOG_CATEGORY);
		
		$db->commit();
		
		return $this->ok();
	}

	/**
	 * 提交货权转移单
	 */
	public function commitGOBill($params) {
		if ($this->isNotOnline()) {
			return $this->notOnlineError();
		}
		
		$db = M();
		$db->startTrans();
		
		$bs = new BizConfigService();
		// true: 先进先出
		$fifo = $bs->getInventoryMethod() == 1;
		
		$id = $params["id"];
		
		$sql = "select id,
					bill_status,
					bizdt,
					biz_user_id,
					from_goodsowner_id,
					to_goodsowner_id,
					date_created,
					input_user_id,
					goods_id,
					goods_count,
					warehouse_id,
					receiving_type,
					sn_note,
					data_org,
					memo,
					bill_memo,
					company_id,
					ref 
				from t_goodsowner_bills where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! data) {
			$db->rollback();
			return $this->bad("要提交的货权转移单不存在");
		}
		$ref = $data[0]["ref"];
		$bizdt = $data[0]["bizdt"];
		$dateCreated = $data[0]["date_created"];
		$billStatus = $data[0]["bill_status"];
		$bizUserId = $data[0]["biz_user_id"];
		$itemId = $data[0]["id"];
		$goodsId = $data[0]["goods_id"];
		$goodsCount = floatval($data[0]["goods_count"]);
		$fromGoodsowneId = $data[0]["from_goodsowner_id"];
		$warehouseId = $data[0]["warehouse_id"];
		$dataOrg = $data[0]["data_org"];
		$toGoodsownerId = $data[0]["to_goodsowner_id"];
		$companyId = $data[0]["company_id"];
		
		if ($billStatus != 0) {
			$db->rollback();
			return $this->bad("货权转移单已经提交，不能再次提交");
		}
		
		$sql = "select name as cnt from t_user where id = '%s' ";
		$data = $db->query($sql, $bizUserId);
		if (! $data) {
			$db->rollback();
			return $this->bad("业务员不存在");
		}
		
		$sql = "select code, name from t_goods where id = '%s' ";
		$data = $db->query($sql, $goodsId);
		if (! $data) {
			$db->rollback();
			return $this->bad("要转移的商品不存在(商品后台id = {$goodsId})");
		}
		$goodsCode = $data[0]["code"];
		$goodsName = $data[0]["name"];
		if ($goodsCount <= 0) {
			$db->rollback();
			return $this->bad("商品[{$goodsCode} {$goodsName}]的转移数量需要是正数");
		}
		
		if(strcmp($fromGoodsowneId, $toGoodsownerId) == 0) {
			$db->rollback();
			return $this->bad("货主相同，无法提交！");
		}
		
		/*****************************下面分为两部分，一是转入部分*************************************/
		// 货权总账
		$sql = "select
					id,
					goodsowner_id,
					balance_count,
					goods_id,
					in_count,
					out_count,
					warehouse_id,
					data_org,
					company_id
				from t_goodsowner_inventory
				where
					goods_id = '%s' and goodsowner_id = '%s'";
		
		$inventoryData = $db->query($sql, $goodsId, $toGoodsownerId);
		if ($inventoryData === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		if($inventoryData) { //如果存在更新
		
			$invId = $inventoryData[0]["id"];
			//插入货主转出信息
			$invBalanceCount = $inventoryData[0]["balance_count"] + $goodsCount;
			$invInCount = $inventoryData[0]["in_count"] + $goodsCount;
				
			$sql = "update t_goodsowner_inventory
						set balance_count = '%s',
							in_count = '%s'
						where id = '%s'";
				
			$inventoryData = $db->execute($sql, $invBalanceCount, $invInCount, $invId);
			if ($inventoryData === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		} else { //如果不存在则插入
			$sql = "insert into t_goodsowner_inventory(
						goodsowner_id,
						balance_count,
						goods_id,
						out_count,
						in_count,
						warehouse_id,
						company_id) values (
							'%s',
							'%f',
							'%s',
							'%f',
							'%f',
							'%s',
							'%s'
						)";
			$inventoryData = $db->execute($sql,$toGoodsownerId,$goodsCount,$goodsId,0,$goodsCount,$warehouseId,$companyId);
			if ($inventoryData === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		}
		
		// 库存明细账
		$sql = "insert into t_goodsowner_inventory_detail(
					goodsowner_id,
					biz_goodsowner_id,
					balance_count,
					biz_date,
					biz_user_id,
					date_created,
					goods_id,
					in_count,
					out_count,
					ref_number,
					ref_type,
					warehouse_id,
					data_org,
					company_id)
				values (
					'%s',
					'%s',
					'%f',
					'%s',
					'%s',
					'%s',
					'%s',
					'%f',
					'%f',
					'%s',
					'%s',
					'%s',
					'%s',
					'%s'
				)";
		$inventoryData = $db->execute($sql,    
				$toGoodsownerId,
				$fromGoodsowneId,
				$goodsCount,
				$bizdt,
				$bizUserId,
				$dateCreated,
				$goodsId,
				$goodsCount,
				0,
				$ref,
				'货权转移',
				$warehouseId,
				$dataOrg,
				$companyId);
		if ($inventoryData === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		
		/*****************************下面分为两部分，二是转出部分*************************************/
		// 货权总账
		$sql = "select 
					id,
					goodsowner_id,
					balance_count,
					goods_id,
					in_count,
					out_count,
					warehouse_id,
					data_org,
					company_id
				from t_goodsowner_inventory 
				where
					goods_id = '%s' and goodsowner_id = '%s'";
		
		$inventoryData = $db->query($sql, $goodsId, $fromGoodsowneId);
		if ($inventoryData === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		if($inventoryData) { //如果存在更新
			 
			$invId = $inventoryData[0]["id"];
			//插入货主转出信息
			$invBalanceCount = $inventoryData[0]["balance_count"] - $goodsCount;
			$invOutCount = $inventoryData[0]["out_count"] + $goodsCount;
			
			$sql = "update t_goodsowner_inventory
						set balance_count = '%s',
							out_count = '%s'
						where id = '%s'";
			
			$inventoryData = $db->execute($sql, $invBalanceCount, $invOutCount, $invId);
			if ($inventoryData === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		} else { //如果不存在则插入
			$sql = "insert into t_goodsowner_inventory(
						goodsowner_id,
						balance_count,
						goods_id,
						out_count,
						in_count,
						warehouse_id,
						company_id) values (
							'%s',
							'%f',					
							'%s',
							'%f',
							'%f',
							'%s',
							'%s'						
						)";
			$inventoryData = $db->execute($sql,$fromGoodsowneId,-$goodsCount,$goodsId,$goodsCount,0,$warehouseId,$companyId);
			if ($inventoryData === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		}
		
		// 库存明细账
		$sql = "insert into t_goodsowner_inventory_detail(
					goodsowner_id,       
					biz_goodsowner_id,   
					balance_count,      
					biz_date, 		   
					biz_user_id,       
					date_created,        
					goods_id,		
					in_count,          
					out_count,		    
					ref_number,		    
					ref_type,		   
					warehouse_id,      
					data_org,		     
					company_id)     
				values (
					'%s',				
					'%s',				
					'%f',				
					'%s',				
					'%s',				
					'%s',				
					'%s',				
					'%f',				
					'%f',				
					'%s',				
					'%s',				
					'%s',				
					'%s',
					'%s'
				)";
		$inventoryData = $db->execute($sql,    $fromGoodsowneId,
									$toGoodsownerId,
									$goodsCount,
									$bizdt,
									$bizUserId,
									$dateCreated,
									$goodsId,
									0,
									$goodsCount,
									$ref,
									'货权转移',
									$warehouseId,
									$dataOrg,
									$companyId);
		if ($inventoryData === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}

		$sql = "update t_goodsowner_bills 
					set bill_status = 1000
					where id = '%s' ";
		$inventoryData = $db->execute($sql, $id);
		if ($inventoryData === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$log = "提交货权转移单，单号 = {$ref}";
		$bs = new BizlogService();
		$bs->insertBizlog($log, $this->LOG_CATEGORY);
		
		$db->commit();
		
		return $this->ok($id);
	}

}